// pages/cart/cart.js
const config = require('../../config.js');
const app = getApp();
const appkey = require('../../appkey.js');
const request = require('../../utils/request.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsLst: [],
    selectAll: 'N',
    del: 'N',
    amount: 0
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCarLstAction(() => { });
  },

  /**
   * 下拉刷新 
   */
  onPullDownRefresh: function () {
    console.log('下拉刷新')
    wx.showNavigationBarLoading();

    this.getCarLstAction(function () {
      //隐藏顶部loading
      wx.hideNavigationBarLoading();
      // 停止下拉动作  
      wx.stopPullDownRefresh();
    });

  },

  selectAction: function (item) {
    var lst = this.data.goodsLst;
    var index = item.target.dataset.index;
    var ids = lst[index].id;
    this.selectOrNot(ids, lst[index].selected);

  },

  selectOrNot: function (ids, flag) {
    var url = '';
    var self = this;
    if (flag == 'Y') {
      url = config.noselectCarUrl;
    } else {
      url = config.selectCarUrl;
    }
    let spk = wx.getStorageSync(require('../../appkey.js').shoppingkey);
    var params = {
      shoppingKey: spk,
      ids: ids
    };
    console.log(params);
    request.requestPost(url, params)
      .then(data => {
        self.getCarLstAction(() => { });
      }).catch(msg => {
      });
  },

  selectAllAction: function () {
    var select = this.data.selectAll;
    var ids = [];
    this.data.goodsLst.map(item => {
      ids.push(item.id);
    });
    this.selectOrNot(ids.join(','), select);
  },

  /**
   * 计算价格
   */
  workTotalPrice: function () {
    var lst = this.data.goodsLst;
    var allSelected = 'Y';
    var del = 'N';
    var total = 0;
    lst.map((item) => {
      if (item.selected == 'Y') {
        total += item.product_shop_price / 100 * item.num;
        del = 'Y';
      } else {
        allSelected = 'N';
      }
    });
    this.setData({
      amount: total,
      selectAll: allSelected,
      del: del
    })
  },


  minusCount: function (e) {
    const index = e.currentTarget.dataset.index;
    var goods = this.data.goodsLst;
    var curGoods = goods[index];
    var count = curGoods.num;
    if (count > 1) {
      var count = curGoods.num - 1;
      this.updateCount(count, curGoods.id);
    }
  },

  addCount: function (e) {
    const index = e.currentTarget.dataset.index;
    var goods = this.data.goodsLst;
    var curGoods = goods[index];
    if (curGoods.product_number > curGoods.num) {
      var count = curGoods.num + 1;
      this.updateCount(count, curGoods.id);
    }
  },

  updateCount: function (num, sid) {
    console.log('count:' + num);
    console.log('id:' + sid);
    wx.showLoading({
      title: '',
    });

    let self = this;
    let goodsLst = this.data.goodsLst;
    let url = config.updateCarNumUrl;
    let spk = wx.getStorageSync(require('../../appkey.js').shoppingkey);
    let params = {
      shoppingKey: spk,
      id: sid,
      count: num
    }
    console.log(params);
    request.requestPost(url, params)
      .then(data => {

        if (data.stock) {
          // 修改列表中数据
          goodsLst.map(item => {
            if (item.id == sid) {
              item.product_number = data.stock
            }
          })
        }

        self.getCarLstAction(() => { });
        wx.hideLoading();
      }).catch(msg => {
        console.log(msg);
        wx.hideLoading();
      });
  },

  changenumAction: function (e) {
    const index = e.currentTarget.dataset.index;
    var goods = this.data.goodsLst;
    var curGoods = goods[index];
    this.updateCount(parseInt(e.detail.value), curGoods.id);
  },

  delDialog: function () {
    var self = this;
    wx.showModal({
      title: '提醒',
      content: '确认要删除吗?',
      success: function (res) {
        if (res.confirm) {
          self.delAction();
        }
      }
    });
  },

  /**
   * 删除
   */
  delAction: function () {
    wx.showLoading({
      title: '正在删除',
    });
    let shopkey = wx.getStorageSync(appkey.shoppingkey);
    let ids = [];

    this.data.goodsLst.map(item => {
      if (item.selected == 'Y') {
        ids.push(item.id);
      }
    })

    let self = this;
    let url = config.delCarUrl;
    let params = {
      shoppingKey: shopkey,
      id: ids.join(',')
    }
    console.log(params);
    request.requestPost(url, params)
      .then(data => {
        self.getCarLstAction();
        wx.hideLoading();
      }).catch(msg => {
        wx.hideLoading();
      });
  },

  getCarLstAction: function (callback) {
    let url = config.carLstUrl;
    let shopkey = wx.getStorageSync(appkey.shoppingkey);
    let params = {
      shopId: app.globalData.shopId,
      shoppingKey: shopkey
    }
    request.requestPost(url, params)
      .then(data => {
        console.log(data);
        this.setData({
          goodsLst: data,
        })
        this.workTotalPrice();
        callback();
      }).catch(msg => {
        console.log(msg);
      });
  },



  /**
   * 购物车结算
   */
  carOrderAction:function(){
    
  },

/**
 * 结算
 */
  settleAction:function(){
    wx.navigateTo({
      url: '../settle/settle',
    })
  }




})